package com.weaver.qfengx;

import cn.hutool.crypto.symmetric.DES;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import java.io.*;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 加解密工具类
 *
 * @Author Qfeng
 * @Date 2020-01-10 22:18:41
 */
public class CryptUtils {

    @Test
    public void test02() throws IOException {
//        List<String> list = Lists.newArrayList("1", "2", "3");
//        System.out.println(Joiner.on(",").skipNulls().join(list.toArray()).toString());
//        System.out.println(CryptUtils.toBase64("123".getBytes("utf-8")));
        String res = "asdsa";
        System.out.println(CryptUtils.md5(res));
        System.out.println(CryptUtils.qihooMD5(res.getBytes(StandardCharsets.UTF_8)));
    }



    @Test
    public void test01() throws IOException {
        File file = new File("C:\\Users\\Qfeng\\Desktop\\upload\\1600570471563.jpg");
        FileInputStream stream = new FileInputStream(file);
        String base64 = toBase64(stream);
        System.out.println(base64);
        File fileOut = new File("C:\\Users\\Qfeng\\Desktop\\upload\\1600570471563.bak.jpg");
        FileOutputStream out = new FileOutputStream(fileOut);
        base64ToStream(base64, out);
    }

    /**
     * 将输入流转为base64
     */
    public static String toBase64(byte[] bytes) throws IOException {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 将输入流转为base64
     */
    public static String toBase64(InputStream inputStream) throws IOException {
        String str = null;
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        return Base64.encodeBase64String(bytes);
    }

    public static byte[] base64ToBytes(String base64) throws IOException {
        byte[] bytes = Base64.decodeBase64(base64);
        return bytes;
    }

    public static void base64ToStream(String base64, OutputStream outputStream) throws IOException {
        byte[] bytes = Base64.decodeBase64(base64);
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        ByteStreams.copy(in, outputStream);
    }

    public static String md5(String txt) {
       return md5(txt.getBytes(StandardCharsets.UTF_8));
    }

    public static String md5(byte[] bytes) {
        byte[] secretBytes = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(bytes);
            secretBytes = messageDigest.digest();
        } catch (Exception e) {
            e.printStackTrace();
        }

        String md5code = new BigInteger(1, secretBytes).toString(16);
        int length = md5code.length();
        for (int i = 0; i < 32 - length; i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static String qihooMD5(byte[] bytes) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(bytes);
            byte tmp[] = mdTemp.digest();
            char strs[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                strs[k++] = hexDigits[byte0 >>> 4 & 0xf];
                strs[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(strs).toLowerCase();
        } catch (Exception e) {
            return null;
        }
    }

    public static String md5(InputStream inputStream) throws IOException {
        return md5(IOUtils.toByteArray(inputStream));
    }

    public static String genSign(Map<String, String> params) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = Lists.newArrayList(params.entrySet());
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            for (Map.Entry<String, String> item : infoIds) {
                if (Objects.nonNull(item) || StringUtils.isNotEmpty(item.getKey())) {
                    String key = item.getKey();
                    Object val = item.getValue();
                    if (StringUtils.isEmpty(result)) {
                        result += String.format("%s=%s", key, val);
                    } else {
                        result += String.format("&%s=%s", key, val);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5(result);
    }

    public static String sha1(String data) {
        return sha1(data.getBytes(StandardCharsets.UTF_8));
    }

    public static String sha1(byte[] data) {
        try {
            MessageDigest digest = MessageDigest
                    .getInstance("SHA-1");
            digest.update(data);
            byte messageDigest[] = digest.digest();
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString().toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String desEncrypt(String content, String key) {
        return desEncrypt(content.getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8));
    }

    public static String desEncrypt(byte[] content, byte[] key) {
        DES des = new DES(key);
        byte[] encrypt = des.encrypt(content);
        return cn.hutool.core.codec.Base64.encode(encrypt);
    }

}
